<template>
  <div>
    <el-dialog title="导入客户" :visible.sync="importVisible" width="436px">
      <div v-if="flag == 'import'">
        <el-form ref="importForm" :model="importForm" :rules="rules" size="medium" :inline="true">
          <div style="margin-top: 20px">
            <div class="textLine">
              1、<a @click="download" class="download">下载模板</a>
              ，按格式准备需要导入的数据
            </div>
            <div style="display: flex" class="textLine">
              2、上传需要导入的文件
              <el-upload action="/" :auto-upload="false" ref="upload" :before-upload="handleBeforeUpload"
                         :data="uploadData" :on-success="uploadSuccess" :on-error="uploaderror" class="uploadText"
              >
                <el-button>
                  <svg-icon iconClass="upload-simple"></svg-icon>
                  <span class="ml5"> 选择文件</span>
                </el-button>
              </el-upload>
            </div>
            <div class="textLine tagInput" style=" display: flex;">
              <span>3、标签</span>

              <tag-group v-model="importForm.weTagGroups" style="flex: 1;margin-left: 10px;" />
            <!--              3、-->
            <!--              <span>打标签</span>-->
            <!--              <el-input v-model="importForm.customerTag" placeholder="请输入"-->
            <!--                        style="width: 236px;margin-left: 10px;"-->
            <!--              ></el-input>-->
            <!--              <div class="inputInfo">输入多个标签以英文;分隔</div>-->
            </div>
          </div>
        </el-form>
      </div>
      <div v-if="flag == 'fail'" class="failArea">
        <div class="failTitle">
          <svg-icon iconClass="info"></svg-icon>
          <!-- <span> 有{{ failList.length }}条错误信息未成功导入！</span> -->
          <span>{{ errorMsg }}</span>
        </div>
        <!-- <div class="failInfoArea">
          <div v-for="(item, index) in failList" :key="index">
            <p>{{ item }}</p>
          </div>
        </div> -->
      </div>
      <div v-if="flag == 'success'" class="successArea">
        <div class="successTitle">
          <svg-icon iconClass="success"></svg-icon>
          <span>成功</span>
        </div>
        <div class="successInfo">{{ successMag }}</div>
      </div>
      <div slot="footer" class="dialog-footer">
        <el-button @click="importVisible = false" v-if="flag == 'import'">取消</el-button>
        <el-button type="primary" @click="handelConfirm" v-preventReClick="1000">{{
            flag == 'import' ? '下一步' : '确定'
          }}
        </el-button>
      </div>
    </el-dialog>
  </div>
</template>
<script>
import { importCus } from '@/api/customer/customerManage'

export default {
  name: 'ImportCustomer',
  components: {},
  props: {
    // 添加标签显隐
    visible: {
      type: Boolean,
      default: false
    },
    isMyCustomer: {
      type: Number,
      default: false
    }
  },
  data() {
    return {
      importForm: {
        // customerTag: undefined
        weTagGroups:[]
      },
      rules: {},
      options: [],
      flag: 'import',
      failList: [],
      uploadData: {},
      successMag: '',
      errorMsg: ''
    }
  },
  computed: {
    importVisible: {
      get() {
        if (this.visible) {
          this.importForm.weTagGroups = []
          this.$nextTick(() => {
            // this.$refs["importForm"].clearValidate();
          })
          this.flag = 'import'
        }
        return this.visible
      },
      set(val) {
        this.$emit('update:visible', val)
      }
    }
  },
  watch: {},
  created() {
  },
  mounted() {
  },
  methods: {
    onOpen() {
    },
    onClose() {
      this.$refs['importForm'].resetFields()
    },
    close() {
      this.$emit('update:visible', false)
    },
    handelConfirm() {
      // console.log('a')
      if (this.flag == 'import') {
        if (this.$refs.upload.$data.uploadFiles.length == 0) return this.$message.error("未选择要上传的文件");
        // if(!this.importForm.weTagGroups || this.importForm.weTagGroups.length == 0) return this.$message.error("未选择要上传的文件");
        // this.uploadData["weTagGroups"] = JSON.stringify(this.importForm.weTagGroups  || []);
        this.$refs.upload.submit()
      } else {
        this.close()
      }
    },
    //下载模板
    download() {
      if (window.globalConfig.ENV === 'production') {
        window.open('https://ark-1308072185.cos.ap-shanghai-fsi.myqcloud.com/scrm/templates/%E5%AE%A2%E6%88%B7%E5%AF%BC%E5%85%A5%E6%A8%A1%E6%9D%BF.xlsx')
      } else {
        window.open('https://test-ztdata-1308072185.cos.ap-shanghai-fsi.myqcloud.com/scrmtest/scrm-upload/%E5%AE%A2%E6%88%B7%E5%AF%BC%E5%85%A5%E6%A8%A1%E6%9D%BF.xlsx')
      }
    },
    handleBeforeUpload(file) {
      this.testTag()
      let formData = new FormData()
      formData.append('file', file)

      // obj.weTagGroups = this.importForm.weTagGroups.map(item=>{
      //   return {
      //     groupName:item.groupName,
      //     groupTagType: '1',
      //     weTags:[{
      //       name:item.tagName
      //     }]
      //   }
      // })
      // formData.append('weTagGroups', JSON.stringify(this.importForm.weTagGroups  || []))
      formData.append('weTagGroups', JSON.stringify(this.importForm.weTagGroups.map(item=>{
        return {
          groupName:item.groupName,
          isMulti:item.isMulti,
          groupTagType: '1',
          weTags:[{
            name:item.tagName
          }]
        }
      })  || []))
      // formData.append('customerTag', this.importForm.customerTag || "")
      // if (this.isMyCustomer === 1) {
      //   formData.append('sysUserId', this.$store.state.user.userId)
      // }
      formData.append('sysUserId', this.$store.state.user.userId || '')
      formData.append('type', this.isMyCustomer)
      importCus(formData)
        .then(res => {
          if (res.code == 200) {
            this.flag = 'success'
            this.successMag = res.msg
          }
        }).catch((res) => {
        this.errorMsg = res.msg
        this.flag = 'fail'
      })
      return false
    },
    testTag() {
      if (this.importForm.customerTag) {
        this.importForm.customerTag = this.importForm.customerTag.replace(
          /^\s*|\s*$/g,
          ''
        )
        if (
          this.importForm.customerTag.indexOf(';') != -1 ||
          this.importForm.customerTag.indexOf('；') != -1
        ) {
          let tagList = []
          let arr = this.importForm.customerTag.split(/[；;]/g)
          arr.forEach((item) => {
            item = String(item).replace(/^\s*|\s*$/g, '')
            if (tagList.indexOf(item) == -1 && item != '') {
              tagList.push(item)
            }
          })
          this.importForm.customerTag = tagList
        } else {
          let tagList = []
          tagList.push(this.importForm.customerTag)
          this.importForm.customerTag = tagList
        }
      }
    },
    //文件上传成功
    uploadSuccess(res) {
      // this.failList = [];
      // if (res.code == 200) {
      //   this.flag = "success";
      //   this.successMag = res.msg;
      // } else if (res.code == 400) {
      //   this.failList = res.data;
      //   this.flag = "fail";
      // }
    },
    //文件上传失败
    uploaderror(res) {
      this.close()
    }
  }
}
</script>

<style lang="scss" scoped>
.textLine {
  margin: 12px;
  line-height: 34px;

  .uploadText {
    margin-left: 10px;
  }
}

.download {
  text-decoration: underline;
  color: #082aff;
}

.tagInput {
  position: relative;
}

.inputInfo {
  position: absolute;
  color: #082aff;
  font-size: 12px;
  right: 48px;
  top: 38px;
}

.failArea {
  .failTitle {
    margin: 16px 22px;
    line-height: 40px;

    .svg-icon {
      font-size: 24px;
    }

    span {
      margin-left: 8px;
    }
  }

  .failInfoArea {
    max-height: 204px;
    overflow: overlay;

    p {
      line-height: 26px;
      text-align: left;
      width: 196px;
      margin: 0 auto;
    }
  }
}

.successArea {
  padding: 40px 30px 30px;

  .successTitle {
    margin: 16px 22px;
    line-height: 40px;

    .svg-icon {
      font-size: 24px;
    }

    span {
      margin-left: 8px;
      font-size: 16px;
      font-weight: 800;
    }
  }

  .successInfo {
    text-align: center;
  }
}
</style>
